package v1

import (
	"fmt"
	"ginblog/errmsg"
	"ginblog/model"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"strconv"
)

/*
	添加用户
	删除用户
	修改用户
	查询全部用户
	查询单个用户
*/

// GetUserById 查看单个用户
func GetUserById(c *gin.Context) {
	var data model.User
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.ViewById(id, &data)
	if code == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"status": code,
			"data":   data,
			"msg":    errmsg.GetErrMsg(code),
		})
	}
	if code == errmsg.ERROR {
		c.JSON(http.StatusOK, gin.H{
			"status": code,
			"msg":    errmsg.GetErrMsg(code),
		})
	}
}

// GetUserAll 查看全部用户
func GetUserAll(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageszie")) //每页个数
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))   //当前页码
	if pageSize == 0 {
		pageSize = -1 //传值-1，就相当于没有这个功能
	}
	if pageNum == 0 {
		pageNum = -1
	}
	data, total := model.GetUsers(pageSize, pageNum)
	code := errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrMsg(code),
	})
}

// AddUser 添加用户
func AddUser(c *gin.Context) {
	var data model.User
	err := c.ShouldBindJSON(&data)
	fmt.Println(&data)
	if err != nil {
		fmt.Println("绑定参数失败", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"status": "failed",
			"msg":    err.Error(),
		})
		logrus.Info("查看成功")
		return
	}
	//// 使用 validator 对结构体进行校验
	//validate := validator.New()
	//if err := validate.Struct(data); err != nil {
	//	// 验证失败，返回错误响应
	//	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	//	return
	//}
	// 判断角色是否是0或1
	//if data.Role != 0 && data.Role != 1 {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"status": "failed",
	//		"msg":    "role must be 0 or 1",
	//	})
	//	return
	//}
	code := model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		fmt.Println("用户添加成功")
		model.CreateUser(&data)
	}
	if code == errmsg.ErrorUsernameUsed {
		fmt.Println("用户已存在")
		code = errmsg.ErrorUsernameUsed
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"data":   data,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// UpdateUser 修改用户(在更新时也需要注意name不能重名)
func UpdateUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var data model.User
	c.ShouldBindJSON(&data)
	code := model.CheckUser(data.Username)
	if code == errmsg.SUCCESS {
		model.UpdateUser(id, &data)
	}
	if code == errmsg.ErrorUsernameUsed {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

// DelUser 删除用户
func DelUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DelUser(id)
	c.JSON(http.StatusOK, gin.H{
		"status": code,
		"msg":    errmsg.GetErrMsg(code),
	})
}

//密码加密
